package com.kalvan.log.util;

import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.PrioritizedParameterNameDiscoverer;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;

import java.lang.reflect.Method;

/**
 * @author chenliang
 */
public final class NameDiscover {

    private static final ParameterNameDiscoverer parameterNameDiscover;

    static {
        parameterNameDiscover = new PrioritizedParameterNameDiscoverer();
        ((PrioritizedParameterNameDiscoverer) parameterNameDiscover)
                .addDiscoverer(new LocalVariableTableParameterNameDiscoverer());
        ((PrioritizedParameterNameDiscoverer) parameterNameDiscover)
                .addDiscoverer(new StandardReflectionParameterNameDiscoverer());
    }

    /**
     * 获取指定类指定方法的参数名
     *
     * @param method 要获取参数名的方法
     * @return 按参数顺序排列的参数名列表，如果没有参数，则返回null
     */
    public static String[] getParameterNames(Method method) {
        String clazzName = method.getDeclaringClass().getName();
        int idx = clazzName.indexOf("$");
        Method m = method;
        if (idx > 0) {
            //如果有代理类的情况下需要自己构建
            clazzName = clazzName.substring(0, idx);
            try {
                m = Class.forName(clazzName).getMethod(method.getName(), method.getParameterTypes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return parameterNameDiscover.getParameterNames(m);
    }

}
